﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GameClient;
using System.Threading;

namespace Submarines
{
    
    public partial class frmGame : Form
    {
        public frmGame()
        {
            InitializeComponent();
            this.SetStyle(

          ControlStyles.AllPaintingInWmPaint |

          ControlStyles.UserPaint |

          ControlStyles.DoubleBuffer, true);

            GameClient.Client.MessageReceived += new Client.GameReceiveHandler(Client_MessageReceived);
            GameClient.Client.ResignReceived += new Client.GameReceiveHandler(Client_ResignReceived);
            GameClient.Client.ReadyAnswer += new Client.GameReceiveHandler(Client_ReadyAnswer);
            
        }

        #region Local_Events
        
        private void Form1_Load(object sender, EventArgs e)
        {
            Diag.AddLog(this.Name, "frmGame loaded with Local=" + Global._Local.ToString());
            Lang.Language(this,typeof(frmGame));
            lstChat.Visible = !Global._Local;
            lblChat.Visible = !Global._Local;
            lblMessage.Visible = !Global._Local;
            txtMyText.Visible = !Global._Local;
            lblOpponentName.BackColor = Color.Transparent;
            lblUserName.BackColor = Color.Transparent;
            lblTimeToHit.BackColor = Color.Transparent;
            lblToHitText.BackColor = Color.Transparent;
            lblChat.BackColor = Color.Transparent;
            lblMessage.BackColor = Color.Transparent;
            picTurn.BackColor = Color.Transparent;
            if (!Global._Local)
            {
                lblUserName.Text = Global._User_name;
                this.Text += "   " + Global._User_name + " vs. " + Global._Opponent_name;    
            }
            else
            {
                this.Text += "    Me"  + " vs. Computer";
                if (Global._Language == "Русский")
                    lblOpponentName.Text = "Компьютер";
                else if (Global._Language == "עברית")
                    lblOpponentName.Text = "מחשב";
                else
                    lblOpponentName.Text = "Computer";
            }
        }

        private void tmrHit_Tick(object sender, EventArgs e)
        {
            Global._TimeToHit -= 1;
            if (Global.stop_game)
            {
                string _mess;
                tmrHit.Enabled = false;
                if (Global._Language == "Русский")
                    _mess = "Поздравляем! Вы выиграли!!!\n\rИграть еще?";
                else if (Global._Language == "עברית")
                    _mess = "?" + "רוצה עוד משחק" + " \n\r!" + "כל הכבוד, נצחת";
                else
                    _mess = "Congratulation!  You WIN!\n\rDo you want another one?";

                DialogResult dr =  MessageBox.Show(_mess, "BattleShip", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dr == DialogResult.Yes)
                    ResetForm();
                else
                    this.Close();
            }
            lblTimeToHit.Text = Global._TimeToHit.ToString();
            if (Global._TimeToHit == 0)
            {
                tmrHit.Enabled = false;
                string _mess;                
                if (Global._Local)
                {
                    if (Global._Language == "Русский")
                        _mess = "Поздравляем! Вы пропустили вашу очередь!";
                    else if (Global._Language == "עברית")
                        _mess = "!"+"פיספסת תור שלך"+" !"+"יופי";
                    else
                        _mess = "Congratulation! You lose your turn!";
                    MessageBox.Show(_mess, "BattleShip", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    AI_Hit();
                    Global.ClearTimer();
                    tmrHit.Enabled = true;
                }
                else
                {
                    if (Global._Language == "Русский")
                        _mess = "Время вышло! Вы проиграли!";
                    else if (Global._Language == "עברית")
                        _mess = "!" + "הפסדת" + " !" + "זמן עבר";
                    else
                        _mess = "The time is up! You lost!";
                    GameClient.Client.Resign();
                    MessageBox.Show(_mess, "BattleShip", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    this.Close();
                }
            }
        }

        private void btnResign_Click(object sender, EventArgs e)
        {
            string _mess;  
            
            if (!Global._Local)
            {
                Diag.AddLog(this.Name, "Client.Resign sent");
                GameClient.Client.Resign();
                tmrHit.Enabled = false;
            }
            else
            {
                ComputerWins();
            }
            if (Global._Language == "Русский")
                _mess = "Играть еще?";
            else if (Global._Language == "עברית")
                _mess = "?" + "רוצה עוד משחק";
            else
                _mess = "Play again?";
            DialogResult dr = MessageBox.Show(_mess, "BattleShip", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == DialogResult.Yes)
                ResetForm();
            else
                this.Close();
        }

        private void txtMyText_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                Diag.AddLog(this.Name, "Client.SendMessage sent-" + txtMyText.Text);
                GameClient.Client.SendMessage(txtMyText.Text);
                lstChat.Items.Add(txtMyText.Text);
                lstChat.SelectedIndex = lstChat.Items.Count - 1;
                txtMyText.Text = "";
                txtMyText.Focus();
            }
        }
     
        private void btnRandomize_Click(object sender, EventArgs e)
        {
            
            tblSetup.Visible = false;
            tblPlayer.InstallSubmarines(true);
            for (int a = 0; a < 8; a++) tblSetup.Controls[a].Enabled = true;
            btnStart.Visible = true;
            
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            
            tblPlayer.Enabled = false;
            btnStart.Visible = false;
            tblSetup.Visible = false;
            tblOpponent.Enabled = true;
            tblOpponent.Visible = true;
            btnRandomize.Visible = false;
            lblTimeToHit.Visible = true;
            lblToHitText.Visible = true;
            btnClean.Visible = false;
            tblOpponent.InstallSubmarines(false);
            picTurn.Visible = true;
            if (Global._Local)
            {
                picTurn.Image = global::Submarines.Properties.Resources.Right;
                Global.ClearTimer();
                tmrHit.Enabled = true;
            }
            else
            {
                Diag.AddLog(this.Name, "Client.Ready sent");
                GameClient.Client.Ready();
            }
        }

        #endregion

        #region Push_Events

        void Client_ReadyAnswer(object sender, ClientEventArgs e)
        {
            tmrHit.Enabled = true;
        }

        void Client_MessageReceived(object sender, ClientEventArgs e)
        {
            lstChat.Items.Add(e.StringValue);
        }
        
         void Client_ResignReceived(object sender, ClientEventArgs e)
        {
            string _mess1, _mess2;
            if (Global._Language == "Русский")
            {
                _mess1 = "Оппонент ";
                _mess2 = " cдался. Вы Победили!!!!";
            }
            else if (Global._Language == "עברית")
            {
                _mess1 = "!"+"נצחת"+"!"+"נכנע";
                _mess2 = " "+"היריב";
            }
            else
            {
                _mess1 = "The opponent ";
                _mess2 = " resigned! You WIN!";
            }
            IWin(_mess1 + Global._Opponent_name + _mess2);
        }

        #endregion

        #region Local_Func

        public void AI_Hit()
        {
            tblOpponent.Enabled = false;
            picTurn.Image = global::Submarines.Properties.Resources.Left;
            this.Refresh();
            Thread.Sleep(500);
            tblPlayer.Next();
            if (tblPlayer.IsGameOver())
            {
                ComputerWins();
            }
            else
            {
                picTurn.Image = global::Submarines.Properties.Resources.Right;
                tblOpponent.Enabled = true;
                tmrHit.Enabled = true;
            }
        }

        void ComputerWins()
        {
            string _mess;
            tmrHit.Stop();
            tmrHit.Enabled = false;
            if (Global._Language == "Русский")
                _mess = "Компьютер победил!";
            else if (Global._Language == "עברית")
                _mess = "!" + "מחשב נצח";
            else
                _mess = "Computer WINS!";
            
            MessageBox.Show(_mess, "BattleShip", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            ResetForm();
        }

        void ResetForm()
        {
            tblOpponent.InitializeSubmarines();
            tblPlayer.InitializeSubmarines();
            tblPlayer.Enabled = true;
            tblSetup.Visible = true;
            tblSetup.Controls.Clear();
            tblSetup.Setup_Load(null, null);
            tblOpponent.Visible = false;
            lblTimeToHit.Visible = false;
            lblToHitText.Visible = false;
            btnRandomize.Visible = true;
            btnClean.Visible = true;
            picTurn.Visible = false;
            Global.stop_game = false;
            tmrHit.Enabled = false;
        }
       
        void IWin(string msg)
        {
            tmrHit.Enabled = false;
            MessageBox.Show(msg, "BattleShip", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            this.Close();
        }

        #endregion

        
        private void frmGame_FormClosing(object sender, FormClosingEventArgs e)
        {
            tmrHit.Enabled = false;
        }

        private void btnClean_Click(object sender, EventArgs e)
        {
            //tblSetup.Setup_Load(null, null);
            //tblSetup.Refresh();
            //    this.Refresh();
            ResetForm();
        }

       
    }
}
